import axios from 'axios'
import qs from 'qs'
import router from '../router/index'

// 响应时间60秒
axios.defaults.timeout = 6000
//axios.defaults.baseURL = 'http://127.0.0.1:9005/markert'
axios.defaults.baseURL = 'http://8.134.130.51:9005/markert'
// 跨域时如果要带上cookie话则需要设置withCrendentials
axios.defaults.withCredentials = false

// http request 拦截器 请求前
axios.interceptors.request.use(
  request => {
    console.log('请求拦截request.data:', request.method);
    // post 请求设置请求头,若不清楚对应 swagger 接口文档请求参数类型
    if (request.method === 'post') {
      // 设置header覆盖content-type
      request.data = qs.stringify(request.data)
      request.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
    }
    return request
  },
  error => {
    // 请求错误时做些事
    return Promise.reject(error)
  }
)

// 响应式时拦截
axios.interceptors.response.use(
  response => {
    if (response.data && response.data.code === '500') {
      // token无效清空token
      localStorage.removeItem('Authorization')
      router.push({ path: '/login', params: { msg: '登录超时' } })
    }
    return response
  },
  error => {
    // 返回响应异常时做一些处理
    return Promise.reject(error)
  }
)

// POST 方法封装 (处理参数与文件上传)
export const postRequest = (url, params) => {
  return axios({
    method: 'post',
    url: url,
    data: params
  }).then(checkStatus)
}

// GET请求
export const getReques = (url, params) => {
  return axios({ method: 'get', url: url, data: params }).then(checkStatus(response))
}

// 错误处理
function checkStatus (response) {
  return new Promise((resolve, reject) => {
    if (response.status === 200) {
      resolve(response.data)
    } else {
      reject(response.data)
    }
  })
}